import { readFileSync, writeFileSync } from 'node:fs'
import path from 'node:path'

function searchDomain(paths) {
  const urlpattern = /(https?:\/\/[^/]*)/i
  const urls = new Set()
  for (const path of paths) {
    const content = readFileSync(path, 'utf-8')
    const matches = content.match(urlpattern)
    if (matches) {
      matches.forEach(match => urls.add(match))
    }
  }
  return urls
}

export default () => {
  return {
    name: 'vite-plugin-preload-img',
    generateBundle(options, bundle) {},
    writeBundle(options, bundle) {
      const assets = Object.values(bundle).map(item => {
        return path.resolve(options.dir, item.fileName)
      })
      const dnsPrefetchList = Array.from(searchDomain(assets)).map(item => {
        return `<link rel="dns-prefetch" href="${item}">`
      })

      const indexPath = path.resolve(options.dir, 'index.html')
      const indexContent = readFileSync(indexPath, 'utf-8')
      const newIndexContent = indexContent.replace('<head>', `<head>\n${dnsPrefetchList.join('')}`)
      writeFileSync(indexPath, newIndexContent)
    },
    // transformIndexHtml(html, ctx) {
    //   if (ctx.server) {
    //     return [
    //       {
    //         tag: 'link',
    //         attrs: { rel: 'preload', href: '/img/1.jpg', as: 'image'}
    //       }
    //     ]
    //   } else {
    //     return html
    //   }
    // }
  }
}
